<!--
 * @Author: 汤米淘大米
 * @Date: 2022-06-24
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2023-06-11
 * @FilePath: /macc.admin.vue/src/views/acceptSharing/userManagement/index.vue
 * @Description: 
-->
<template>
  <div class="accept-wrapper">
    <a-card style="width: 600px" :bodyStyle="{ padding: '0' }">
      <div class="top flex row-center">
        <img
          class="logo"
          src="@/assets/images/common/ruijieCloud.png"
          width="95"
          alt=""
        />
        <img
          class="mt-35"
          src="@/assets/images/common/cardTopBg.png"
          width="270"
          alt=""
        />
      </div>
      <h1 class="text-center mt-20">{{ title }}</h1>
      <!-- <h3 class="text-center">
        Shared by <span style="color: #2b6afd">xxx</span> @mial.com to you
      </h3>  -->
      <p class="plr-30">
        You are invited to receive the user management. And you can complete the
        account management of empoyess by yourself easily.
      </p>
      <p class="text-center" v-if="submitDisabled" style="color: #ec4d3e">
        {{ errorTxt }}
      </p>
      <!-- <p class="plr-30" v-if="mode === ''">{{ $t('acceptUmSharing.tip2') }}</p> -->
      <div v-if="hasLogin">
        <div class="p-20 text-right">
          <a-button @click="cancelSharing">{{ $t('common.cancel') }}</a-button>
          <a-button type="primary" @click="acceptSharing">{{
            $t('common.ok')
          }}</a-button>
        </div>
      </div>
      <div v-else>
        <a-form-model
          ref="generalForm"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 12 }"
          @submit="handleSubmit"
          :model="formData"
          :rules="rules"
        >
          <a-form-model-item :label="$t('common.email')" prop="email">
            <a-input v-model="formData.email" />
          </a-form-model-item>

          <a-form-model-item
            :label="$t('common.password')"
            prop="password"
            v-if="mode === 'login' || mode === 'register'"
          >
            <a-input-password v-model="formData.password" autocomplete="off" />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('common.pwdConfirm')"
            v-if="mode === 'register'"
            prop="pwdConfirm"
          >
            <a-input-password
              v-model="formData.pwdConfirm"
              autocomplete="off"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('common.verification')"
            v-show="showVerifyCode"
            prop="verifyCode"
          >
            <a-input v-model="formData.verifyCode" />
            <img
              @click="changeSecurityCode"
              id="validateImg"
              src=""
              alt=""
              style="cursor: pointer"
            />
          </a-form-model-item>
          <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
            <a-button
              type="primary"
              html-type="submit"
              :disabled="submitDisabled"
            >
              {{ acceptBtnTxt }}
            </a-button>
            <a-button
              v-show="mode === 'login'"
              type="link"
              @click="toSignUp()"
              >{{ $t('acceptUmSharing.goSignUp') }}</a-button
            >
            <a-button
              v-show="mode === 'register'"
              type="link"
              @click="toSignIn()"
              >{{ $t('acceptUmSharing.goSignIn') }}</a-button
            >
          </a-form-item>
        </a-form-model>
      </div>
    </a-card>
    <!-- <iframe id="mock_login" :src="mockLoginUrl" style="display: none"></iframe> -->
  </div>
</template>

<script>
import { requestHttp, request } from '@utils/index';
const CURR_MODE = {
  LOGIN: 'login',
  REGISTER: 'register',
};

export default {
  name: 'UserManagement',
  data() {
    let validatePsw = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('common.pwdTip')));
      } else {
        if (this.formData.pwdConfirm !== '') {
          this.$refs.generalForm.validateField('pwdConfirm');
        }
        callback();
      }
    };
    let validatePswConfirm = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('common.pwdConfirmTip')));
      } else if (value !== this.formData.password) {
        callback(new Error(this.$t('common.pwdNotMatch')));
      } else {
        callback();
      }
    };

    let validPwdStrength = (rule, value, callback) => {
      // eslint-disable-next-line
      const pwdStrengthRegex =
        /^(?![a-zA-z]+$)(?!\d+$)(?![`~!@#\$%\^\&\*\(\)_\+<>\?:"\{\},\.\\\/;'\[\]\-]+$)[a-zA-Z\d`~!@#\$%\^\&\*\(\)_\+<>\?:"\{\},\.\\\/;'\[\]\-]+$/;
      // eslint-disable-next-line
      if (pwdStrengthRegex.test(value)) {
        callback();
      } else {
        callback(
          new Error(
            'The password must contain at least two of the following types of characters: letters, numbers, and special characters.'
          )
        );
      }
    };
    return {
      errorTxt: '',
      submitDisabled: false,
      acceptBtnTxt: this.$t('acceptUmSharing.accept'),
      mockLoginUrl: location.origin,
      title: this.$t('acceptUmSharing.title'),
      eShareCode: '',
      hasLogin: true,
      firstLogin: false,
      mode: CURR_MODE.LOGIN,
      formData: {
        email: '',
        password: '',
        pwdConfirm: '',
        address: '',
        timeZone: '',
        verifyCode: '',
      },
      showVerifyCode: false,
      rules: null,
      loginRules: {
        email: [
          {
            type: 'email',
            message: this.$t('common.emailInvalid'),
          },
          {
            required: true,
            message: this.$t('common.emailTip'),
          },
        ],
        password: [
          {
            required: true,
            message: this.$t('common.pwdTip'),
          },
        ],
      },
      registerRules: {
        email: [
          {
            type: 'email',
            message: this.$t('common.emailInvalid'),
          },
          {
            required: true,
            message: this.$t('common.emailTip'),
          },
        ],
        password: [
          {
            required: true,
            message: this.$t('common.pwdTip'),
          },
          {
            min: 5,
            max: 12,
            message: this.$t('acceptUmSharing.pwdLengthInvalid'),
            trigger: 'blur',
          },
          { validator: validatePsw, trigger: 'change' },
          { validator: validPwdStrength },
        ],
        pwdConfirm: [
          {
            required: true,
            message: this.$t('common.pwdConfirmTip'),
          },
          { validator: validatePswConfirm, trigger: 'change' },
        ],
      },
    };
  },
  watch: {
    mode: function (newD, oldD) {
      if (newD === CURR_MODE.LOGIN) {
        this.acceptBtnTxt = this.$t('acceptUmSharing.accept');
        this.rules = this.loginRules;
      } else {
        this.acceptBtnTxt = this.$t('acceptUmSharing.signUpAndAccept');
        this.rules = this.registerRules;
      }
    },
  },
  mounted() {
    this.eShareCode = location.hash.match(/code=(\w+)/)[1];
    this.getSharerInfo();
    if (location.hash.match(/account=(.+)/)) {
      const account = location.hash.match(/account=(.+)/)[1];
      this.formData.email = decodeURIComponent(account);
      this.hasLogin = true;
    } else {
      this.hasLogin = false;
    }

    this.getFirstLoginStatus();
    this.rules = this.loginRules;
  },
  methods: {
    toSignUp() {
      this.mode = CURR_MODE.REGISTER;
    },
    toSignIn() {
      this.mode = CURR_MODE.LOGIN;
    },
    handleSubmit(e) {
      e.preventDefault();
      this.$refs.generalForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        switch (this.mode) {
          case CURR_MODE.REGISTER:
            this.zhugePoint('macc-用户管理-通过注册方式接受分享', {
              workId: 'maccNetConf',
              funcId: 'macc-userMng',
            });
            this.register();
            break;
          case CURR_MODE.LOGIN:
          default:
            this.zhugePoint('macc-用户管理-通过登录方式接受分享', {
              workId: 'maccNetConf',
              funcId: 'macc-userMng',
            });
            this.login();
            break;
        }
      });
    },

    async login() {
      const params = {
        username: this.formData.email,
        password: this.formData.password,
        verifyCode: this.formData.verifyCode,
      };

      if (process.env.NODE_ENV === 'production') {
        params.service = location.origin + '/admin3/';
      } else {
        params.service = 'https://cloudtest-as.ruijienetworks.com/admin3/';
      }

      const st = await request('/webproxy/sso/getSt', 'POST', params);
      if (st?.code === -98) {
        this.$message.error(st.msg);
        this.refreshVerifyCode(true);
        return;
      }

      if (st.includes('http')) {
        this.$message.error(this.$t('common.loginError'));
        this.refreshVerifyCode(true);
        return;
      }

      const { code, msg } = await this.setBindingCode();
      if (code === 0) {
        if (process.env.NODE_ENV === 'production') {
          location.href = `${location.origin}/admin3/?ticket=${st}`;
        } else {
          location.href = `https://cloudtest-as.ruijienetworks.com/admin3/?ticket=${st}`;
        }
        // document
        //   .getElementById('mock_login')
        //   .contentWindow.easyLoginAfterRegister(
        //     params.username,
        //     params.password
        //   );
      } else {
        this.$message.error(msg);
      }
    },

    /**
     * @description:
     * @return {*}
     */
    async register() {
      const params = {
        email: this.formData.email,
        account: this.formData.email,
        address: this.formData.address,
        language: 'en',
        remark: 'unknown',
        phone: 88888888,
        timezone: this.formData.timeZone,
        firstName: 'unknown',
        lastName: 'unknown',
        password: this.formData.password,
        source: 'WEB',
        verifyCode: this.formData.verifyCode,
      };

      const api = `/internationalRegister/unauthentication/tenant/signUp`;
      const { code, msg } = await requestHttp(
        {
          api: api,
          method: 'POST',
          params: params,
        },
        {},
        'preLogin'
      );

      if (code === 0) {
        this.login();
      } else {
        this.$message.error(msg);
      }
    },

    changeSecurityCode() {
      var imgSrc = document.getElementById('validateImg');

      let href = '';
      if (process.env.NODE_ENV === 'production') {
        href = `${location.origin}`;
      } else {
        href = `https://cloudtest-as.ruijienetworks.com`;
      }

      let src = `${href}/webproxy/verifyCode/getCode?_=` + new Date().getTime();
      imgSrc.setAttribute('src', src);
    },

    //触发网络执行流量识别任务
    async getFirstLoginStatus() {
      let { code } = await request(
        '/webproxy/verifyCode/isFisrtLogin',
        'POST',
        {}
      );
      if (code === 0) {
        this.firstLogin = true;
      } else {
        this.refreshVerifyCode();
      }
    },

    refreshVerifyCode(showVerifyCode) {
      if (showVerifyCode) {
        this.showVerifyCode = true;
      } else if (
        (this.mode === CURR_MODE.LOGIN || this.mode === CURR_MODE.REGISTER) &&
        !this.firstLogin
      ) {
        this.showVerifyCode = true;
      }

      if (!this.showVerifyCode) {
        return;
      }

      this.changeSecurityCode();
      this.rules.verifyCode = [
        {
          required: true,
          message: this.$t('common.pwdTip'),
        },
      ];
    },

    //触发网络执行流量识别任务
    async acceptSharing() {
      this.zhugePoint('macc-用户管理-登录后点击接受分享', {
        workId: 'maccNetConf',
        funcId: 'macc-userMng',
      });
      debugger;
      const { code, msg } = await this.setBindingCode();
      if (code === 0) {
        if (process.env.NODE_ENV === 'production') {
          window.location.href = location.origin + '/admin3/';
        } else {
          window.location.href =
            'https://cloudtest-as.ruijienetworks.com/admin3/';
        }
      } else {
        this.$message.error(msg);
      }
    },

    async setBindingCode() {
      const api = `/intl/unauth/easy/share/account/set_bind`;
      const params = {
        email: this.formData.email,
        code: this.eShareCode,
      };
      return await requestHttp(
        {
          api: api,
          method: 'POST',
          params,
        },
        {},
        'preLogin'
      );
    },

    cancelSharing() {
      if (process.env.NODE_ENV === 'production') {
        window.location.href = location.origin + '/admin3/';
      } else {
        window.location.href =
          'https://cloudtest-as.ruijienetworks.com/admin3/';
      }
    },

    async getSharerInfo() {
      const api = `/intl/unauth/easy/share/account/info/{code}`;
      const { code, msg, address, timeZone } = await requestHttp(
        {
          api: api,
          method: 'GET',
          replaces: {
            code: this.eShareCode,
          },
        },
        {},
        'preLogin'
      );

      if (code === 0) {
        this.formData.address = address;
        this.formData.timeZone = timeZone;
      } else {
        this.submitDisabled = true;
        this.errorTxt = msg;
        // this.$message.error(msg);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.accept-wrapper {
  background: url('~@assets/images/common/bigBg.png') center bottom / cover !important;
  height: 100%;
  min-height: 720px;
  display: flex;
  align-items: center;
  justify-content: center;
  .top {
    position: relative;
    height: 180px;
    background: #f6f8fc;
    .logo {
      position: absolute;
      left: 26px;
      top: 20px;
    }
  }
}
.main-content {
  width: 600px;
  min-height: 300px;
  border-radius: 8px;
  position: relative;
  box-shadow: 0 0 26px rgba(0, 0, 0, 0.36);
  background-color: #fff;
}

.remoteCode_title {
  font-size: 16px;
  font-weight: bold;
  padding: 0 16px;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #e5e5e5;
}

.tac_Content {
  padding: 16px;
}

.ant-btn + .ant-btn {
  margin-left: 16px;
}

#validateImg {
  width: 90px;
  height: 30px;
}
.flex {
  display: flex;
}
.row-center {
  justify-content: center;
}
.text-center {
  text-align: center;
}
.mt {
  margin-top: 20px;
}
.p {
  padding: 20px;
}
.text-right {
  text-align: right;
}
.mt-35 {
  margin-top: 35px;
}
.plr-30 {
  padding: 0 30px;
}
.p-20 {
  padding: 20px;
}
</style>
